import { onMounted, reactive, ref, unref } from 'vue';
import { post } from '@/utils/http';

export function useHttp<T>(url: string, initialParams: any) {
  const dataList = ref<T[]>([]);
  const loading = ref<boolean>(false);
  const totals = ref<number>(0);
  const pageInfo = reactive({
    page: 1,
    pageSize: 10,
  });

  const loadData = async () => {
    loading.value = true;
    try {
      const {
        data: { list, total },
      } = await post(url, {
        ...unref(initialParams),
        ...pageInfo,
      });

      dataList.value = list;
      console.log("👿 ~ loadData ~ dataList.value:", dataList.value)
      totals.value = total;
    } catch (error) {
      console.log('👿 ~ loadData ~ error:', error);
    } finally {
      loading.value = false;
    }
  };

  const handleSizechange = (size: number) => {
    pageInfo.pageSize = size;
    loadData();
  };
  const handlePageNochange = (pageNo: number) => {
    pageInfo.page = pageNo;
    loadData();
  };

  const resetPagination = () => {
    pageInfo.page = 1;
    pageInfo.pageSize = 10;
    loadData();
  };
  onMounted(()=>{
    loadData()
  })

  return {
    dataList,loading,totals,pageInfo,loadData,handleSizechange,handlePageNochange,resetPagination
  }
}
